package com.huanzhidadi.single.completablefuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 计算完成后续操作
 * 线程队列返回的是whenComplete方法之前的结果
 * CompletableFuture<T> whenComplete(BiConsumer<? super T, ? super Throwable> action)
 * CompletableFuture<T>中的T代表入参的T，也就是返回的是入参的T，跟自身的返回值无关
 */
public class WhenCompleteTest {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(100);
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("前置程序子线程：" + Thread.currentThread().getName());
            return "123";
        }, executorService).whenComplete((v, e) -> {
            if (e == null) {
                System.out.println(v + "无异常：" + Thread.currentThread().getName());
            } else {
                System.out.println(v + "有异常：" + Thread.currentThread().getName());
            }
            System.out.println("后续程序子线程2：" + Thread.currentThread().getName());
            v = v + "456";
            System.out.println(v);
        });
        try {
            String s = future.get();
            System.out.println("执行结果：" + s);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("主线程结束：" + Thread.currentThread().getName());
        executorService.shutdown();
    }
}
